package com.batchengine.task;

import static com.batchengine.DataAdapter.FILE;
import com.batchengine.Definitions;
import com.batchengine.cron.ScheduledJobParser;
import static com.batchengine.task.RecurringJobParser.getTaskDataParser;
import static com.batchengine.task.TaskContext.createTaskContext;

import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by  solutions
 * Author: sunil.incubator@yahoo.com
 * Date: Aug 7, 2009
 */
public class TaskUtil {

    private static Map<Long, RecurringJob> recurringJobMap = null;
    private static Map<Long, ScheduledJob> scheduledJobMap = null;

    private TaskUtil() {
    }

    public static TaskContext getTaskContext(Long taskId) {
        return createTaskContext(taskId);
    }

    public static RecurringJob getRecurringJob(Long jobId) {

        if (null == recurringJobMap) {
            recurringJobMap = getRecurringJobMap();
        }
        return recurringJobMap.get(jobId);
    }

    public static ScheduledJob getScheduledJob(Long jobId) {

        if (null == scheduledJobMap) {
            scheduledJobMap = getScheduledJobMap();
        }
        return scheduledJobMap.get(jobId);
    }

    public static Map<Long, RecurringJob> getRecurringJobMap() {

        if (null == recurringJobMap) {

            RecurringJobParser jobDataParser = getTaskDataParser(FILE);
            recurringJobMap = jobDataParser.loadRecurringJobMap();
        }
        return recurringJobMap;
    }

    public static Map<Long, ScheduledJob> getScheduledJobMap() {

        if (null == scheduledJobMap) {

            ScheduledJobParser jobDataParser = ScheduledJobParser.getCronDataParser(Definitions.DataAdapter.FILE);
            Collection<ScheduledJob> datas = jobDataParser.loadData();
            scheduledJobMap = new ConcurrentHashMap<Long, ScheduledJob>();
            if (null != datas) {
                for (ScheduledJob cronData : datas) {

                    ScheduledJob job = new ScheduledJob(cronData.getJobId());
                    job.setMinWorkers(cronData.getMinWorkers());
                    job.setMaxWorkers(cronData.getMaxWorkers());
                    job.setInstanceName(cronData.getInstanceName());
                    TaskInfo taskInfo = TaskParser.getTaskDataParser(FILE).getTaskConfigurationMap().get(cronData.getTaskInfo().getTaskId());
                    job.setTaskInfo(taskInfo);
                    scheduledJobMap.put(cronData.getJobId(), job);
                }
            }
        }
        return scheduledJobMap;
    }

    public static void main(String[] args) {

        Map<Long, ScheduledJob> map = getScheduledJobMap();
        Set<Long> longs = map.keySet();
        for (Long aLong : longs) {
            System.out.println(map.get(aLong));
        }
    }

}
